<template>
  <div class="inventory-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>药材库存管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增库存</el-button>
            <el-button @click="loadData">刷新</el-button>
          </div>
        </div>
      </template>

      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="药材">
            <el-select v-model="searchForm.herbId" placeholder="请选择药材" clearable filterable>
              <el-option
                  v-for="herb in herbList"
                  :key="herb.herbId"
                  :label="herb.herbName"
                  :value="herb.herbId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="批次号">
            <el-input v-model="searchForm.batchNumber" placeholder="请输入批次号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="inventoryId" label="ID" width="80" />
        <el-table-column prop="herbName" label="药材名称" />
        <el-table-column prop="batchNumber" label="批次号" />
        <el-table-column prop="quantity" label="数量(g)" />
        <el-table-column prop="unitPrice" label="单价">
          <template #default="{ row }">
            ￥{{ row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseDate" label="采购日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.purchaseDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="过期日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.expirationDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="daysUntilExpiry" label="剩余天数" width="100">
          <template #default="{ row }">
            <el-tag :type="getExpiryTagType(row.daysUntilExpiry)">
              {{ row.daysUntilExpiry }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAvailable" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.isAvailable ? 'success' : 'danger'">
              {{ row.isAvailable ? '可用' : '不可用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pageParams.page"
            v-model:page-size="pageParams.pageSize"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {herbInventoryApi, chineseHerbApi} from '@/api/admin'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const herbList = ref([])
const total = ref(0)

const searchForm = reactive({
  herbId: null,
  batchNumber: ''
})

const pageParams = reactive({
  page: 1,
  pageSize: 10
})

// 加载库存数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await herbInventoryApi.page(
        searchForm.herbId,
        searchForm.batchNumber,
        pageParams.page,
        pageParams.pageSize
    )
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error('加载库存数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载药材列表
const loadHerbs = async () => {
  try {
    const res = await chineseHerbApi.page('', null, 1, 10)
    herbList.value = res.data.records || []
  } catch (error) {
    console.error('加载药材列表失败:', error)
  }
}

const handleSearch = () => {
  pageParams.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    herbId: null,
    batchNumber: ''
  })
  pageParams.page = 1
  loadData()
}

const handleAdd = () => {
  router.push('/admin/herb-inventory/add')
}

const handleEdit = (row) => {
  router.push(`/admin/herb-inventory/edit/${row.inventoryId}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除库存记录"${row.herbName}-${row.batchNumber}"吗？`,
        '警告',
        {type: 'warning'}
    )

    await herbInventoryApi.delete(row.inventoryId)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    // 用户取消操作
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const getExpiryTagType = (days) => {
  if (days < 0) return 'danger'
  if (days <= 30) return 'warning'
  return 'success'
}

const handlePageChange = () => {
  loadData()
}

const handleSizeChange = () => {
  pageParams.page = 1
  loadData()
}

// 页面挂载时加载数据
onMounted(() => {
  loadData()
  loadHerbs()
})
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
